package jinbao.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jinbao.pojo.domain.User;
import jinbao.pojo.dto.PageDTO;
import jinbao.pojo.query.UserQuery;
import jinbao.pojo.request.UserUpdateRequest;
import jinbao.pojo.vo.UserListItemVO;
import jinbao.service.UserService;
import jinbao.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static jinbao.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author Mr.zeng
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-03-11 22:34:33
 */
@Service
@Slf4j//日志注解
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final String SALT = "jinbao";//加密延值
    @Autowired
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //检测非空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return -1;
        }
        //检测长度和两次密码是否一致
        if (userAccount.length() != 8 || userPassword.length() != 6 || !userPassword .equals( checkPassword) ){
            return -1;
        }
        //检测账户是否包含特殊字符
        String str = ".*[\\s`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？\\\\]+.*";
        Matcher matcher = Pattern.compile(str).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        //检测账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            return -1;
        }
        //密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        //设置默认参数
        user.setUsername("未知");
        boolean result = this.save(user);
        if (!result) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        //检测长度
        if (userAccount.length() != 8 || userPassword.length() != 6) {
            return null;
        }
        //检测账户是否包含特殊字符
        String str = ".*[\\s`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？\\\\]+.*";
        Matcher matcher = Pattern.compile(str).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }

        //密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("user login failed: userAccount cannot match userPassword");
            return null;
        }

        //用户脱敏,隐藏敏感信息
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUserAuthority(user.getUserAuthority());


        //记录用户的登录状态
        HttpSession session = request.getSession();
        session.setAttribute(USER_LOGIN_STATE, user);


        return safetyUser;
    }

    @Override
    public List<User> searchUsers(String username) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        return list(queryWrapper.like("username",username));
    }

    @Override
    public PageDTO<UserListItemVO> userList(UserQuery userQuery) {
        String username=userQuery.getUsername();
        String userAccount = userQuery.getUserAccount();
        Integer userStatus = userQuery.getUserStatus();
        Integer userAuthority = userQuery.getUserAuthority();
        Integer gender = userQuery.getGender();
        String phone = userQuery.getPhone();
        //构建分页条件
        Page<User> page=Page.of(userQuery.getCurrentPage(),userQuery.getPageSize());

        //分页查询
        Page<User> p=lambdaQuery()
                .like(username != null, User::getUsername, username)
                .eq(userAccount != null, User::getUserAccount, userAccount)
                .eq(userStatus != null, User::getUserStatus, userStatus)
                .eq(userAuthority != null, User::getUserAuthority, userAuthority)
                .eq(gender != null, User::getGender, gender)
                .eq(phone != null, User::getPhone, phone)
                .page(page);
        PageDTO<UserListItemVO> userPageDTO=new PageDTO<>();
        userPageDTO.setTotal(p.getTotal());
        userPageDTO.setPages(p.getPages());
        //当前页数据
        List<User> records = p.getRecords();
        //DO拷贝为VO
        if(CollectionUtils.isEmpty(records)){
            userPageDTO.setList(Collections.emptyList());
        }else {
            List<UserListItemVO> vos=new ArrayList<>();
            for (User record : records) {
                UserListItemVO itemVO=new UserListItemVO();
                BeanUtils.copyProperties(record,itemVO);
                vos.add(itemVO);
            }
            userPageDTO.setList(vos);
        }
        return userPageDTO;
    }

    @Override
    public boolean deleteUser(Integer[] id) {
        for (int i : id) {
            int i1 = userMapper.deleteById(i);
            if(i1<=0){
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean updateUser(UserUpdateRequest userUpdateRequest) {
        UpdateWrapper<User> wrapper=new UpdateWrapper<>();
        wrapper.eq("userAccount",userUpdateRequest.getUserAccount())
                .set("userStatus",userUpdateRequest.getUserStatus())
                .set("userAuthority",userUpdateRequest.getUserAuthority());
        int update = userMapper.update(wrapper);
        return update > 0;
    }



}




